﻿using System.Windows;
using System.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using Channel9WrapperLibrary;

namespace C9ShowNotesHelper
{
  /// <summary>
  /// Interaction logic for FindShow.xaml
  /// </summary>
  public partial class FindEpisode : Window
  {
    List<Channel9WrapperLibrary.Episode> episodelist = new List<Channel9WrapperLibrary.Episode>();
    int currentshowpage = 1;

    BackgroundWorker _backgroundWorker = new BackgroundWorker();
    
    public Channel9WrapperLibrary.Episode SelectedEpisode { get; set; }
    public string ShowUrl { get; set; }
    public string C9UserID { get; set; }
    public string C9UserKey { get; set; }
    
    public FindEpisode()
    {
      InitializeComponent();
      
     }

    private void okButton_Click(object sender, RoutedEventArgs e)
    {
      CloseForm();
    }

    private void cancelButton_Click(object sender, RoutedEventArgs e)
    {
      CancelForm();
    }

    private void refreshButton_Click(object sender, RoutedEventArgs e)
    {
      RefreshShowList();
    }

    void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
      List<Episode> showpage = null;

      try
      {
        showpage = Channel9WrapperLibrary.Shows.GetShowEpisodes(
          this.ShowUrl,
          C9UserID,
          C9UserKey,
          (int)e.Argument
          );

      }
      catch (System.Exception ex)
      {
        MessageBox.Show("Error getting Episodes: " + ex.Message);
        throw;
      }

      e.Result = showpage;
    }

    void _backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
       
      if (e.Cancelled)
      {
        //statusText.Text = "Cancelled";
      }
      else if (e.Error != null)
      {
        statusLabel.Content = e.Error.Message;
      }
      else
      {
        //statusText.Text = "Completed";
        List<Channel9WrapperLibrary.Episode> showpage = (List<Channel9WrapperLibrary.Episode>)e.Result;
        episodelist.AddRange(showpage);
        listBox1.ItemsSource = episodelist;
        listBox1.Items.Refresh();

        if (_backgroundWorker.CancellationPending)
          return;

        //if (showpage.Count>0 )
        //{
        //  currentshowpage += 1;
        //  statusLabel.Content = "Loading Show Page " + currentshowpage.ToString();
        //  _backgroundWorker.RunWorkerAsync(currentshowpage);
        //}
        //else
          statusLabel.Content = "";
      }
    }

    private void listBox1_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
      CloseForm();
    }

    void CloseForm()
    {
      if (listBox1.SelectedItem != null)
        SelectedEpisode = (Channel9WrapperLibrary.Episode)listBox1.SelectedItem;

      if (_backgroundWorker.IsBusy)
        _backgroundWorker.CancelAsync();

      this.DialogResult = true;
      this.Close();

    }

    void CancelForm()
    {
      if (_backgroundWorker.IsBusy)
        _backgroundWorker.CancelAsync();

      SelectedEpisode = null;

      this.DialogResult = false;
      this.Close();
    }

    void RefreshShowList()
    {
      listBox1.ItemsSource = null;
      listBox1.Items.Refresh();

      currentshowpage = 1;
      episodelist.Clear();

      _backgroundWorker.RunWorkerAsync(currentshowpage);
    }

    private void filterTextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
    {
      var results = episodelist
        .Where(d => d.Title.ToUpperInvariant().Contains(filterTextBox.Text.ToUpperInvariant()))
        .ToList();

      listBox1.ItemsSource = null;
      listBox1.ItemsSource = results;
      listBox1.Items.Refresh();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
      _backgroundWorker.DoWork += _backgroundWorker_DoWork;
      _backgroundWorker.RunWorkerCompleted += _backgroundWorker_RunWorkerCompleted;
      _backgroundWorker.WorkerSupportsCancellation = true;

      statusLabel.Content = "Loading Episode Page " + currentshowpage.ToString();
      this.Title = this.Title + " for " + this.ShowUrl;

      _backgroundWorker.RunWorkerAsync(currentshowpage);

    }

    private void nextPageButton_Click(object sender, RoutedEventArgs e)
    {
      currentshowpage += 1;
      statusLabel.Content = "Loading Page " + currentshowpage.ToString();
      _backgroundWorker.RunWorkerAsync(currentshowpage);
 
    }

  }
}
